package wiki.kaizen.cloud.plugin.spring.util;


import org.apache.commons.lang3.time.DateUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.time.*;
import java.util.Date;

import static com.alibaba.fastjson.util.TypeUtils.castToDate;

/**
 *  Temporal 工具类
 *  转 LocalDateTime /LocalDate /LocalTime 工具类
 *
 * @author xeepoo
 *
 */
public class LocalTemporalUtil {

    /*
    * 尽量完整的解析日期
    * 后面遇到在进行补充
    * */
    public static Date parseDateAsPossible(Object source){
        if (source==null){
            return null;
        }
        if (source instanceof String){
            try {
                return  parseDateAsPossible((String)source);
            } catch (ParseException ignore) {}
        }

        try {
            return castToDate(source);
        }catch (Exception e){
            throw new RuntimeException("日期解析异常: 原始值:" +source);
        }
    }

    public static Date parseDateAsPossible (String source) throws ParseException {
        if (StringUtils.isEmpty(source)){
            return null;
        }

        return DateUtils.parseDateStrictly(source,

                "yyyy",
                "yyyy年",

                "yyyyMM",
                "yyyy年MM月",
                "yyyy-MM",

                "yyyyMMdd",
                "yyyy年MM月dd日",
                "yyyy-MM-dd",

                "yyyyMMddHH",
                "yyyy年MM月dd日HH时",
                "yyyy-MM-dd HH",

                "yyyyMMddHHmm",
                "yyyy年MM月dd日HH时mm分",
                "yyyy-MM-dd HH:mm",

                "yyyyMMddHHmmss",
                "yyyy年MM月dd日HH时mm分ss秒",
                "yyyy-MM-dd HH:mm:ss"

        );
    }

    /**
     *date 转为 localDateTime
     */
    public static LocalDateTime dateToLocaDateTime(Date date){
        if (date==null){
            return null;
        }
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        return LocalDateTime.ofInstant(instant, zone);
    }
    /*
    * string 转为 localDateTime
    * */
    public static LocalDateTime strToLocaDateTime(Object source){
        return dateToLocaDateTime(parseDateAsPossible(source));
    }
    /*
    * string 转为 localDate
    * */
    public static LocalDate strToLocaDate(Object source){
        LocalDateTime localDateTime = dateToLocaDateTime(parseDateAsPossible(source));

        return localDateTime==null?null:localDateTime.toLocalDate();
    }
    /*
    * string 转为 localDateTime
    * */
    public static LocalTime strToLocaTime(Object source){
        LocalDateTime localDateTime = dateToLocaDateTime(parseDateAsPossible(source));
        return localDateTime==null?null:localDateTime.toLocalTime();
    }



}
